<?php
namespace App\Http\Controllers\Admin;

use App\Models\News;
use App\Http\Resources\Admin\News as NewsCollection;
use Illuminate\Http\Request;

class NewsController extends Controller
{
    protected $_rules = [
        [
            'title' => 'required|string|max:100',
            'image' => 'required|string',
            'link' => 'required|max:255',
            'app_id' => 'nullable|max:20',
            // 'sort' => 'nullable|integer',
            'is_display' => 'nullable|integer|between:0,1',
            'jump_type' => 'required|integer|between:0,2',
            'platform' => 'required|integer|between:0,3',
        ],
    ];

    public function index()
    {
        $orderBy = $this->getOrderByQuery([
            'id',
            'platform',
            'jump_type',
            'is_display',
        ]);

        $result = News::orderByRaw($orderBy)
        ->orderByDesc('id')
        ->paginate(per_page());
        return new NewsCollection($result);
    }

    public function store(Request $request)
    {
        $inputs = $this->validate($request, $this->_rules[0]);

        $record = News::create($inputs);

        return $record;
    }

    public function update(Request $request, $id)
    {
        $record = News::findOrFail($id);

        $inputs = $this->validate($request, $this->allowNullRules($this->_rules[0]));

        $inputs = $this->unsetEmptyFields($inputs, ['image']);

        $record->update($inputs);
        return $record;
    }

    public function destroy($id)
    {
        $item = News::findOrFail($id);
        $result = News::destroy($id);
        return [];
    }
}
